package com.langyiquan.backed.controller;

import com.langyiquan.bo.SysUserBO;
import com.langyiquan.bo.SysUserInfoBO;
import com.langyiquan.exception.http.ExistException;
import com.langyiquan.exception.http.ParamException;
import com.langyiquan.pojo.SysUser;
import com.langyiquan.service.SysUserService;
import com.langyiquan.utils.DateUtil;
import com.langyiquan.utils.JwtHandler;
import com.langyiquan.utils.UnifyResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Api(value = "系统管理人员", tags = {"系统管理人员相关接口"})
@RestController
@RequestMapping("sysUser")
public class SysUserController extends BaseController{

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private Environment env;

    @ApiOperation(value = "用户名是否存在",notes = "用户名是否存在",httpMethod = "GET")
    @GetMapping("/usernameIsExist")
    public UnifyResponse usernameIsExist(@RequestParam String username){

        if(StringUtils.isBlank(username)){
            throw new ParamException(1001);
        }

        boolean isExist = sysUserService.queryUsernameIsExist(username);
        if(isExist){
            throw new ExistException(1014);
        }

        return UnifyResponse.success();
    }


    @ApiOperation(value = "登录系统用户",notes = "登录系统用户",httpMethod = "POST")
    @PostMapping("/login")
    public UnifyResponse login(@RequestBody SysUserBO sysUserBO, HttpServletRequest request, HttpServletResponse response){
        String username = sysUserBO.getUsername();
        String password = sysUserBO.getPassword();
        if(StringUtils.isBlank(username)){
            throw new ParamException(1001);
        }

        if(StringUtils.isBlank(password)){
            throw new ParamException(1002);
        }

        // 设置操作IP
        sysUserBO.setOperateIp(getIpAddress(request));

        SysUser sysUser = sysUserService.querySysUserForLogin(sysUserBO);
        if(sysUser == null){
            throw new ParamException(1003);
        }
        String token = JwtHandler.sign(sysUser.getId(), 60L* 1000L* 30L);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        return UnifyResponse.success(tokenMap);
    }


    @ApiOperation(value = "获取系统用户信息",notes = "获取系统用户信息",httpMethod = "GET")
    @GetMapping("info")
    public UnifyResponse info(HttpServletRequest request){
        Integer sysUserId = getPassportUserId(request);
        SysUser sysUser = sysUserService.querySysUserInfo(sysUserId);
        return UnifyResponse.success(sysUser);
    }


    @ApiOperation(value = "根据Id系统用户信息",notes = "根据Id系统用户信息",httpMethod = "GET")
    @GetMapping("getInfoById")
    public UnifyResponse getInfoById(@RequestParam Integer sysUserId){
        if(sysUserId == null){
            throw new ParamException(1011);
        }
        SysUser sysUser = sysUserService.querySysUserInfo(sysUserId);
        return UnifyResponse.success(sysUser);
    }


    @ApiOperation(value = "注册系统用户",notes = "注册系统用户",httpMethod = "POST")
    @PostMapping("/register")
    public UnifyResponse register(@RequestBody @Valid SysUserInfoBO sysUserInfoBO, BindingResult bindingResult, HttpServletRequest request){

        if(bindingResult.hasErrors()){
            Map<String,String> errorsMap = getBindingResultErrors(bindingResult);
            String errCode = errorsMap.entrySet().iterator().next().getValue();
            throw new ParamException(Integer.parseInt(errCode));
        }

        // 设置操作IP
        sysUserInfoBO.setOperatorIp(getIpAddress(request));
        sysUserInfoBO.setOperatorId(getPassportUserId(request));
        SysUser sysUser = sysUserService.createSysUser(sysUserInfoBO);
        String token = JwtHandler.sign(sysUser.getId(), 60L* 1000L* 30L);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        return UnifyResponse.success(tokenMap);
    }

    @ApiOperation(value = "更改系统用户信息",notes = "更改系统用户信息",httpMethod = "POST")
    @PostMapping("/update")
    public UnifyResponse update(@RequestBody @Valid SysUserInfoBO sysUserInfoBO, BindingResult bindingResult, HttpServletRequest request){

        if(bindingResult.hasErrors()){
            Map<String,String> errorsMap = getBindingResultErrors(bindingResult);
            String errCode = errorsMap.entrySet().iterator().next().getValue();
            throw new ParamException(Integer.parseInt(errCode));
        }

        // 设置操作IP
        sysUserInfoBO.setOperatorIp(getIpAddress(request));
        sysUserInfoBO.setOperatorId(getPassportUserId(request));
        SysUser sysUser = sysUserService.updateSysUserInfo(sysUserInfoBO.getId(),sysUserInfoBO);
        String token = JwtHandler.sign(sysUser.getId(), 60L* 1000L* 30L);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        return UnifyResponse.success(tokenMap);
    }


    @ApiOperation(value = "上传用户头像",notes = "上传用户头像",httpMethod = "POST")
    @PostMapping("uploadFace")
    public UnifyResponse uploadFace(MultipartFile file, HttpServletRequest request){

        Integer sysUserId = getPassportUserId(request);

        String fileSpace = env.getProperty("resource.upload-location");

        String uploadPathPrefix = File.separator + "faces" + File.separator;

        if(file != null){

            FileOutputStream fileOutputStream = null;

            String fileName = file.getOriginalFilename();

            String fileNameArr[] = fileName.split("\\.");

            String suffix = fileNameArr[fileNameArr.length - 1];

            if(!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg") && !suffix.equalsIgnoreCase("gif")){
                throw new ParamException(1006);
            }

            String newFileName = "face-" + sysUserId + "." + suffix;

            // 上传的头像最终保存的位置
            String finalFacePath = fileSpace + uploadPathPrefix + File.separator + newFileName;
            uploadPathPrefix += ("/"+newFileName);

            File outFile = new File(finalFacePath);
            if (outFile.getParentFile() != null) {
                // 创建文件夹
                outFile.getParentFile().mkdirs();
            }

            // 文件输出保存到目录
            try {
                fileOutputStream = new FileOutputStream(outFile);
                InputStream inputStream = file.getInputStream();
                IOUtils.copy(inputStream, fileOutputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String imageServerUrl = env.getProperty("resource.server-url");

            String avatarUrl = imageServerUrl+uploadPathPrefix;
            sysUserService.updateSysUserFace(sysUserId,avatarUrl);
            Map<String,String> avatarMap = new HashMap<>();
            avatarMap.put("avatarUrl",avatarUrl+"?time="+ DateUtil.getCurrentDateString(DateUtil.DATE_PATTERN));
            return UnifyResponse.success(avatarMap);
        }else{
            throw new ParamException(1007);
        }

    }
}
